package com.leet.code.lcof;

public class Code43 {

    public static void main(String[] args) {
        System.out.println(new Code43().countDigitOne(123123));
        System.out.println(new Code43().test(1, 123123));

    }

    private int countDigitOne(int n) {
        if (n <= 9) {
            return 1;
        }
        String s = String.valueOf(n);
        char[] cs = s.toCharArray();
        int sum;
        if (cs[0] == '1') {
            sum = Integer.parseInt(s.substring(1)) + 1;
        } else {
            sum = pow(s.length() - 1);
        }

        for (int i = 1; i < s.length(); i++) {
            if (cs[i] > '1') {
                int j = Integer.parseInt(s.substring(0, i)) + 1;
                sum = sum + j * (pow(s.length() - i - 1));
            } else if (cs[i] == '1') {
                int j = Integer.parseInt(s.substring(0, i));
                String a = s.substring(i + 1);
                if ("".equals(a)) {
                    a = "0";
                }
                sum = sum + j * (pow(s.length() - i - 1)) + Integer.parseInt(a) + 1;
            } else {
                int j = Integer.parseInt(s.substring(0, i));
                sum = sum + j * (pow(s.length() - i - 1));
            }
        }
        return sum;

    }

    public int pow(int i) {
        StringBuilder sb = new StringBuilder("1");
        for (; i > 0; i--) {
            sb.append("0");
        }
        return Integer.parseInt(sb.toString());
    }

    public int test(int i, int n) {
        int sum = 0;
        for (; i <= n; i++) {
            for (char c : String.valueOf(i).toCharArray()) {
                if (c == '1') {
                    sum++;
                }
            }
        }
        return sum;
    }

}
